package com.css.devops.service.jenkins;

import java.io.IOException;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.devops.exception.EntityExistException;
import com.css.devops.service.DevopsView;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.View;

import lombok.extern.slf4j.Slf4j;

/**
 * View(视图) 相关操作
 *
 * 例如对视图的增、删、改、查等操作
 */
@Slf4j
@Service("jenkinsViewService")
public class JenkinsViewService implements DevopsView {

    /**
     * Jenkins 对象
     */
	@Autowired
    private JenkinsServer jenkinsServer;
    /**
     * Jenkins http 客户端对象
     */
	@Autowired
    private JenkinsHttpClient jenkinsHttpClient;

    /**
     * 创建视图
     */
    @Override
	public void createView(com.css.devops.domain.View view) {
        try {
        	com.css.devops.domain.View viewReponse = this.getView(view.getName());
        	if(Objects.nonNull(viewReponse)) {
        		throw new RuntimeException("已经存在视图！");
        	}
            // 创建一个 xml 字符串，里面设置一个 view 描述信息
            String xml = "<listView _class=\"hudson.model.ListView\">\n" +
                    "<description>%s</description>\n" +
                    "</listView>";
            xml = String.format(xml, view.getDescription());
            // 创建 view
            jenkinsServer.createView(view.getName(), xml, Boolean.TRUE);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new EntityExistException(JenkinsViewService.class,view.getName(),e.getMessage());
        }
    }

    /**
     * 获取视图基本信息
     */
    @Override
	public com.css.devops.domain.View getView(String viewName) {
    	com.css.devops.domain.View viewReponse = null;
        try {
            // 获取视图基本信息
            View view = jenkinsServer.getView(viewName);
            
            viewReponse = new com.css.devops.domain.View();
            view.setName(viewName);
            viewReponse.setName(view.getName());
            viewReponse.setUrl(view.getUrl());
            viewReponse.setDescription(view.getDescription());
        } catch (IOException e) {
        	log.error(e.getMessage(), e);
        	throw new EntityExistException(JenkinsViewService.class,viewName,e.getMessage());
        }
        return viewReponse;
    }
    
    /**
     * 获取视图配置 XML 信息
     */
    @Override
	public String getViewConfig(String viewName) {
    	String viewConfigXml = StringUtils.EMPTY;
        try {
            // 获取视图配置xml信息
            viewConfigXml = jenkinsHttpClient.get("/view/" + viewName + "/config.xml");
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
        	throw new EntityExistException(JenkinsViewService.class,viewName,e.getMessage());
        }
        return viewConfigXml;
    }

    /**
     * 更新视图信息
     */
    @Override
	public void updateView(com.css.devops.domain.View view) {
        try {
            // 创建一个 xml 字符串，里面设置一个要修改的某些字段,具体xml可以到jenkins查看
            // 例如，下面xml文件是从地址：http://192.168.94.1:18080/view/test-view/config.xml 获取的
            String xml = "<hudson.model.ListView>\n" +
                    "<name>test-view</name>\n" +
                    "<description>%s</description>\n" +
                    "<filterExecutors>false</filterExecutors>\n" +
                    "<filterQueue>false</filterQueue>\n" +
                    "<properties class=\"hudson.model.View$PropertyList\"/>\n" +
                    "<jobNames>\n" +
                    "<comparator class=\"hudson.util.CaseInsensitiveComparator\"/>\n" +
                    "</jobNames>\n" +
                    "<jobFilters/>\n" +
                    "<columns>\n" +
                    "<hudson.views.StatusColumn/>\n" +
                    "<hudson.views.WeatherColumn/>\n" +
                    "<hudson.views.JobColumn/>\n" +
                    "<hudson.views.LastSuccessColumn/>\n" +
                    "<hudson.views.LastFailureColumn/>\n" +
                    "<hudson.views.LastDurationColumn/>\n" +
                    "<hudson.views.BuildButtonColumn/>\n" +
                    "<hudson.plugins.favorite.column.FavoriteColumn plugin=\"favorite@2.3.2\"/>\n" +
                    "</columns>\n" +
                    "<recurse>false</recurse>\n" +
                    "</hudson.model.ListView>";
            xml = String.format(xml, view.getDescription());
            jenkinsServer.updateView(view.getName(), xml);
        } catch (IOException e) {
        	log.error(e.getMessage(), e);
        	throw new EntityExistException(JenkinsViewService.class,view.getName(),e.getMessage());
        }
    }

    /**
     * 删除视图
     */
    @Override
	public void deleteView(String viewName) {
        try {
            jenkinsHttpClient.post("/view/" + viewName + "/doDelete", Boolean.TRUE);
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
        	throw new EntityExistException(JenkinsViewService.class,viewName,e.getMessage());
        }
    }
}
